package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.ProgressBar;

import com.lily.aidouzixun.R;
import com.lily.aidouzixun.bean.ArticleInfo;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.MyWebView;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.webview.MyWebViewFragment;
import com.lily.aidouzixun.webview.WebViewConstans;

import java.lang.ref.WeakReference;

/**
 * 文章详情
 * 传参：url
 *      title
 *      showback
 */
public class ArticleDetailActivity extends FragmentActivity {
    private static final String TAG = "MyWebViewActivity";
    private static MyHandler mHandler;

    private Activity mActivity;
    private Context mContext;

    private MyWebViewFragment myWebViewFragment;

    private String curUrl = ""; //当前url
    private ArticleInfo longDistanceInfo;
    private String title = "";  //Fragent标题

    private String backTitle = "";  //返回标题
    private boolean showBack = false;   //是否显示关闭
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        setContentView(R.layout.framelayout_single);
        getIntentData();
        addWebViewFragment();
    }
    private void init() {
        mContext = ArticleDetailActivity.this;
        mActivity = ArticleDetailActivity.this;
        mHandler = new MyHandler(mActivity);
    }

    /**
     * 得到Intent传递过来的参数
     */
    public void getIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            curUrl = intent.getStringExtra(MyConstant.IntentKey.WEBVIEW_URL);
            longDistanceInfo = intent.getParcelableExtra(MyConstant.IntentKey.LONGDISTANCE_INFO);
            title = intent.getStringExtra(MyConstant.IntentKey.TITLE);
            backTitle = intent.getStringExtra(MyConstant.IntentKey.BACK_TITLE);
            showBack = intent.getBooleanExtra(MyConstant.IntentKey.WEBVIEW_SHOWBACK, false);
        }
    }

    /**
     * 添加WebViewFragment
     */
    private void addWebViewFragment() {

        try {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            myWebViewFragment = new MyWebViewFragment();
            Bundle args = new Bundle();
            args.putString(MyConstant.IntentKey.WEBVIEW_URL, curUrl);
            args.putString(MyConstant.IntentKey.TITLE, title);
            args.putString(MyConstant.IntentKey.BACK_TITLE, backTitle);
            args.putBoolean(MyConstant.IntentKey.WEBVIEW_SHOWBACK, showBack);
            args.putBoolean(MyConstant.IntentKey.WEBVIEW_SHARE, true);
            //增加接口
            args.putString(MyConstant.IntentKey.WEBVIEW_INTERFACE, WebViewConstans.InterfaceName.LONGDISTANCE_DETAIL);
            myWebViewFragment.setArguments(args);
            fragmentTransaction.replace(R.id.fl_content, myWebViewFragment);
            fragmentTransaction.commitAllowingStateLoss();
        } catch (Exception e) {
            L.e(TAG, "addWebViewFragment-->error!");
        }
    }

    /**
     * 启动一个WebViewActivity
     * @param context
     *  @param longDistanceInfo
     * @param url
     * @param title
     * @param backTitle
     * @param showBack
     */
    public static void startWebViewActivity(Context context, ArticleInfo longDistanceInfo, String url, String title, String backTitle, boolean showBack) {
        if (!HardWare.isNetworkAvailable(context)) {
            T.shortToast(context, "请检查你的网络！");
            return ;
        }
        Intent intent = new Intent(context, ArticleDetailActivity.class);
        intent.putExtra(MyConstant.IntentKey.WEBVIEW_URL, url);
        intent.putExtra(MyConstant.IntentKey.LONGDISTANCE_INFO, longDistanceInfo);
        intent.putExtra(MyConstant.IntentKey.TITLE, title);
        intent.putExtra(MyConstant.IntentKey.BACK_TITLE, backTitle);
        intent.putExtra(MyConstant.IntentKey.WEBVIEW_SHOWBACK, showBack);
        context.startActivity(intent);
    }

    public static MyHandler getHandler() {
        return mHandler;
    }

    /**
     * 接收信息
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case MyConstant.IntentForResultCODE.LONGDISTANCE_COMMENT_RESULTCODE:    //评论完成,重新加载网页
                myWebViewFragment.getMyWebView().reload();
                break;
            case MyConstant.IntentForResultCODE.LONGDISTANCE_REWARD_REQUESTCODE:    //赞赏完成,重新加载网页
                myWebViewFragment.getMyWebView().reload();
                break;
            default:
                break;
        }
    }

    /**
     * WebView 页面对物理回退键的监听
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            MessageDispatcher.sendMessage(myWebViewFragment.getHandler(), MessageType.ON_KEY_DOWN);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final ArticleDetailActivity activity = (ArticleDetailActivity) mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框

                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框

                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成

                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
}
